//
//  AuthController.swift
//  myBlog
//
//  Created by mac2014 on 16/3/22.
//  Copyright © 2016年 AD. All rights reserved.
//


/// 登录授权界面

/// 加载webview，并在webview中进行授权操作
import UIKit

import SVProgressHUD

let client_id = "2873415267"

let client_secret = "3d1c8eb864a40d98aa3703128bb495c9"

/// 授权回调地址
let redirect_uri = "http://www.baidu.com/"

class AuthController: UIViewController {
    override func loadView() {
        //view = webview后，不用设置约束。webview的大小和当前view的大小一样
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        //设置导航栏
        setupNavigationBar()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
        
        //显示提示页面
        SVProgressHUD.showWithStatus("正在加载")
    }
    
    //填充和取消按钮的点击事件
    //自动加载账号密码
    func didiClickTofullFill() {
        let loginCode = "document.getElementById('userId').value='1364635006@qq.com';document.getElementById('passwd').value='wys910212'"
        
        //执行
        webView.stringByEvaluatingJavaScriptFromString(loginCode)
    }
    
    //
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //设置导航栏
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "didiClickTofullFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    
    //懒加载
    lazy var webView: UIWebView = UIWebView()

}

extension AuthController: UIWebViewDelegate {
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭提示
        SVProgressHUD.dismiss()
    }
    
    
    //是否要加载某个请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        
        if !urlString.hasPrefix(redirect_uri) {
            return true
        } else {
            let query = request.URL?.query
            let codeString = "code="
            
            if query!.hasPrefix(codeString) {
                let nsQuery = query! as NSString
                
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                
                
                //ADUserAcountViewModel.sharedInstance.loadAccessToken(code)
                ADUserAcountViewModel.sharedInstance.loadAccessToken(code, completion: { (error) -> () in
                    if error != nil {
                        print("获取access_token失败: \(error)")
                        SVProgressHUD.showErrorWithStatus("获取access_token失败")
                        //关闭界面
                        self.close()
                    }
                    //没有错误，关闭界面，跳转到mainViewController
                    self.close()
                    AppDelegate.jumpToSpecifiedViewController(ADWelComeController())
                })
            
            }else {
                //点击的是取消，关闭界面
                close()
                
                
            }
            return false
            
        }
  
    }
    
}
